<?php

require_once(dirname(__FILE__) . '/../config.php');
require_once(APPLICATION_ROOT . "/cart/cartclass.php");
require_once(APPLICATION_ROOT . "/items.php");

if ($_GET) $_POST = $_GET;

# WordPress integration.
if (BSDDS_WORDPRESS_INTEGRATION) {
	require_once(APPLICATION_ROOT . "/wp-blog-header.php");
}

# Start the session.
session_start();
$cart =& $_SESSION['cart']; # Point $cart to session cart.

# Ensure we have a valid cart object.
if (!is_object($cart)) $cart = new shoppingCart();

# Sanitize the common inputs.
$add_cart = filter_var($_POST['add_cart'], FILTER_SANITIZE_STRING);
$item_name = filter_var($_POST['item_name'], FILTER_SANITIZE_STRING);
$this_page = filter_input(INPUT_SERVER, 'PHP_SELF', FILTER_SANITIZE_URL);

# Ensure that the return URL is set.
if (!$_SESSION['return_url']) {
	$_SESSION['return_url'] = WEB_ROOT;
}

# Are we adding something to the cart?
if ($add_cart) {
	# Yes, we are.

	# Sanitize the item-related inputs.
	$item_number = (int)filter_var($_POST['item_number'], FILTER_SANITIZE_NUMBER_INT);
	$quantity = (float)filter_var($_POST['quantity'], FILTER_SANITIZE_NUMBER_INT);
	$amount = (float)filter_var($_POST['amount'], FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION);

	# Ensure that the product ID is valid.
	if (!array_key_exists($item_number, $products)) {
		die('Invalid product specified.');
	}

	$product = $products[$item_number];

	# Extract the product prices and formats.
	$product_prices = array_key_exists('price', $product) ? $product['price'] : Array('0');
	$product_formats = array_key_exists('formats', $product) ? $product['formats'] : Array('Any');

	$formats = split(',', $product_formats);
	$prices  = split(',', $product_prices);

	# Validate the amount against known item prices and the quantity.
	$matched_price = FALSE;
	foreach ($prices as $price) {
		$price = (float)trim($price);
		if (($price * $quantity) == $amount) {
			$matched_price = TRUE;
		}
	}

	# Exit if we didn't find a matching price.
	if (!$matched_price) {
		die("Invalid price $amount given.");
	}

	# Ensure that the given format is valid for this product.
	$format = trim(filter_var($_POST['os0'], FILTER_SANITIZE_STRING));
	$matched_format = FALSE;
	foreach ($formats as $allowed_format) {
		if ($format == trim($allowed_format)) {
			$matched_format = TRUE;
		}
	}

	# Exit if we didn't find a matching price.
	if (!$matched_format) {
		die("Invalid price $format given.");
	}

	# Pull the shipping information out of the product definitions.
	$shipping_cad = array_key_exists('shipping_cad', $product) ? $product['shipping_cad'] : 0;
	$shipping_int = array_key_exists('shipping_int', $product) ? $product['shipping_int'] : 0;
	$shipping_usd = array_key_exists('shipping_usd', $product) ? $product['shipping_usd'] : 0;
	$shipping_each = array_key_exists('shipping_each', $product) ? $product['shipping_each'] : 0;

	# Get the return URL.
	$returnURL = filter_var($_POST['return'], FILTER_SANITIZE_URL);

	# Sanity check the values being put through.
	if (($amount >= 0) && ($item_number > 0) && ($quantity > 0) && ($shipping_usd >= 0) && ($shipping_cad >= 0) &&
	    ($shipping_int >= 0) && ($shipping_each >= 0)) {
		$cart->add_item($item_name, $amount, $item_number, $quantity,
		                Array("shipping_usd" => $shipping_usd, "shipping_cad" => $shipping_cad,
		                      "shipping_int" => $shipping_int, "shipping_each" => $shipping_each),
		                $format);
	}

	if ($returnURL) {
		$_SESSION['return_url'] = $returnURL;
	}

}

# Process any POST variables.
if ($_POST) {

	# Sanitize the POST variables.
	$clear_cart = filter_var($_POST['clear_cart'], FILTER_SANITIZE_STRING);
	$remove = filter_var($_POST['remove'], FILTER_SANITIZE_STRING);
	$shipping = filter_var($_POST['shipping'], FILTER_SANITIZE_STRING);
	$update = filter_var($_POST['update'], FILTER_SANITIZE_STRING);

	# If we've been told to clear the cart, do so.
	if ($clear_cart) {
		$cart->clear_cart();
	}

	# If we've been told to update the cart, do so.
	if ($update) {
		# Remove any items we've been told to remove.
		if ($remove) {
			foreach ($remove as $removeID) {
				$cart->remove_item(filter_var($removeID, FILTER_SANITIZE_NUMBER_INT));
			}
		}

		# Update quantities.
		foreach ($cart->itemIDs as $itemID) {
			$cart->itemQuantities[$itemID] =
				filter_var($_POST['qty_' . $itemID], FILTER_SANITIZE_NUMBER_INT);

			if ($cart->itemQuantities[$itemID] == 0) {
				$cart->remove_item($itemID);
			}
		}

		$cart->update_total();
	}

	$select = "selected_" . $shipping;
	$$select = "SELECTED";

}

setcookie("inCart", $cart->total, 0, "/");

?>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
	<head>
		<title>Shopping Cart</title>
	</head>
	<body>
<?php

/* Short and sweet */
# require('../wp-blog-header.php');
# get_header();

# print_r($cart);

?>
		<script src="<?php echo WEB_ROOT; ?>js/jquery-1.2.1.js" type="text/javascript"></script>
		<!--
		<script type="text/javascript">
			// var $j = jQuery.noConflict();
			function calculateShipping(dollar) {

				var shipping = 0;
				var id = 0;
				var shipping_each = new Array();
				var temp = 0;
				var quantity = 0;
				var itemship = 0;
				var additional_shipping = 0;
				var subtotal = 0;

				// get all the shipping_each vars
				$('input[name$=_each]').each(function () {
					id = $(this).attr('value');
					itemid = $(this).attr('class');
					shipping_each[itemid] = id;
				});

				// get the quantity
				$('input[name$=' + dollar + ']').each(function () {
					id = $(this).attr('class');
					quantity = $('#qty_' + id).attr('value');
					itemship = $(this).attr('value');
					shipping += parseInt(itemship);

					if(quantity > 1 & itemship > 0) {
						additional_shipping = (shipping_each[id] * itemship) * quantity-1;
						shipping = shipping + additional_shipping;
					}
				});

				shipping = shipping.toFixed(2);
				$('#shippingtotal').html(shipping);
				$('#shippingpaypal').attr({value: shipping});

				subtotal = $('#subtotal').html();
				subtotal = parseFloat(subtotal) + parseFloat(shipping);
				subtotal = subtotal.toFixed(2);
				$('#total').html(subtotal);

			}

			$(document).ready(function(){
				calculateShipping($('#shipping').attr('value'));
			});
		</script>
		-->
		<div id="outline">
			<div id="fullcontent">

				<h1>Shopping Cart</h1>

<?php
if ($cart->get_contents()) {

	print <<<CART
				<p><strong>Items in cart</strong></p>
				<form action="{$this_page}" method="post" id="shoppingcart">
					<table cellpadding="2" cellspacing=2 width="100%" style="border-style: hidden;" summary="Shopping Cart">
						<tr bgcolor="#CCDDEE">
							<td>Quantity</td>
							<td>Remove</td>
							<td>Item</td>
							<td>Price</td>
						</tr>
CART;

	foreach ($cart->get_contents() as $item) {

		print <<<HTML

						<tr bgcolor="white">

HTML;
		$temp_price = $item['price'] * $item['qty'];
		$price = number_format($temp_price, 2);

		$paypalItems .= "(" . $item['qty'] . ") " . $item['info'] . " ";

		$productid = htmlentities($item['productid']);
		$shipping_usd = htmlentities($item['shipping_usd']);
		$shipping_cad = htmlentities($item['shipping_cad']);
		$shipping_int = htmlentities($item['shipping_int']);
		$shipping_each = htmlentities($item['shipping_each']);

		$hiddenfields = print <<<HIDDEN
							<td align="center" width="8%">
								<input type="hidden" name="shipping_usd" class="{$productid}" value="{$shipping_usd}">
								<input type="hidden" name="shipping_cad" class="{$productid}" value="{$shipping_cad}">
								<input type="hidden" name="shipping_int" class="{$productid}" value="{$shipping_int}">
								<input type="hidden" name="shipping_each" class="{$productid}" value="{$shipping_each}">
HIDDEN;
		$qty = htmlentities($item['qty']);
		$info = htmlentities($item['info']);
		$out_price = htmlentities($price);
		$format = htmlentities($item['format']);
		print <<<CART
		  						<input name="qty_{$productid}" id="qty_{$productid}" type="text" value="{$qty}" size="1" maxlength="3">
							</td> 
							<td align="center" width="1%">
								<input type='checkbox' name='remove[]' value='{$productid}'>
							</td>
							<td align="left" width="38%" class="smalltext">
								<span class="em106">{$info}</span><br>
								Format: $format
							</td>
							<td align="center" width="10%" class="smalltext">
								\${$out_price}
							</td>
						</tr>					
CART;

	}

	$total = htmlentities(number_format($cart->total,2));

	print <<<HTML

						<tr bgcolor="#F2F2F2">
							<td align=center>
								<input type="submit" name="update" value="Update cart">
							</td>
							<td>
								<input type="submit" name="clear_cart" value="Clear cart">
							</td>
							<td colspan="2" align="right">
								Subtotal: \$<span id="subtotal">$total</span>
							</td>
						</tr>
HTML;

	if ($cart->is_shipping()) {
		print <<<HTML

						<tr bgcolor="#F2F2F2">
							<td colspan="4" align="right">
								<select style="font-size: 10px;" name="shipping" id="shipping" onChange="calculateShipping(this.value);\">
									<option value="usd" $selected_usd>United States</option>
									<option value="cad" $selected_cad>Canada</option>
									<option value="int" $selected_int>International</option>
								</select>
								&nbsp;shipping: \$<span id="shippingtotal">0.00</span>
							</td>
						</tr>
HTML;
	}

	$total = htmlentities(number_format($cart->total,2));

	print <<<HTML

						<tr bgcolor="#F2F2F2">
							<td colspan="4" align="right">
								Total: <span style="font-size: 25px; font-weight: bold;">\$<span id="total">$total</span></span>
							</td>
						</tr>
					</table>
				</form>

HTML;

	# Display checkout button if they're paying more than $0.
	if ($cart->total > 0.00) {
		if (BSDDS_AMAZON_PAYMENTS) {
			$cart->output_pay_button_form("amazon");
		}
		if (BSDDS_PAYPAL_PAYMENTS) {
			$cart->output_pay_button_form("paypal");
		}
	} else {
		// If it's zero, ping notify.php?
		$cart->output_free_form();
	}
} else {
	print <<<HTML
				<p>There are no items in your cart!
	
HTML;
}

$return_url = $_SESSION['return_url'];
?>

				<p><a href="<?php echo $return_url; ?>"><strong>&laquo; Continue shopping.</strong></a></p>
			</div>
		</div>
	</body>
</html>